package org.example.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.example.pojo.*;
import org.example.pojo.vo.MomentVo;
import org.example.pojo.vo.NoteVo;
import org.example.service.*;
import org.example.utils.Current;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.sql.Time;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("note")
//@CrossOrigin(origins = "*")  // 允许所有来源
public class NoteController 
{
	
	@Autowired
	NotesService notesService;
	
	@Autowired
	UsersService usersService;
	
	@Autowired
	LikesService likesService;
	
	private static final String FEED_PREFIX = "feed:";
	/**
	 *	发布笔记
	 */
	@GetMapping("publish")
	public Result publish(HttpSession httpSession, @RequestParam String title,@RequestParam String text)
	{
		Object uid = httpSession.getAttribute("uid");
		Notes notes = new Notes();
		notes.setTitle(title);
		notes.setContent(text);
		notes.setLikeCount(0);
		notes.setUserId(Integer.parseInt(uid.toString()));
		notesService.save(notes);
		//feed推送
		//给每个粉丝推送
		//1.找到每个粉丝ID
		QueryWrapper qw = new QueryWrapper();
		qw.eq("following_id", uid);
		List<UserFollows> following_id = userFollowsService.list( qw );
		//2.将写入reids中
		following_id.forEach( u ->{
			stringRedisTemplate.opsForZSet().add(FEED_PREFIX+u.getUserId(),notes.getId().toString(),System.currentTimeMillis());
		});
		
		return Result.ok();
	}

	/**
	 * 删除笔记
	 */
	@GetMapping("del")
	public Result del(HttpSession httpSession,@RequestParam Integer noteId) {
		Integer uid = (Integer)httpSession.getAttribute("uid");
		if(uid == null)
		{
			return Result.error("请登录");
		}
		//判断是不是自己的笔记，否则不能删除
		QueryWrapper qw = new QueryWrapper();
		qw.eq("user_id",uid);
		qw.eq("id",noteId);
		boolean remove = notesService.remove(qw);
		//清除redis数据
		stringRedisTemplate.delete(NOTE_LIKED_PREFIX + noteId);
		return remove?Result.ok("删除成功"):Result.error("删除失败");
	}
	

	/**
	 * 笔记列表
	 */
	@GetMapping("list")
	public Result list(HttpSession httpSession)
	{
		//select n.*,users.username from notes as n left join users on n.user_id = users.id
		//查询是否点过赞
		Integer uid = (Integer)httpSession.getAttribute("uid");

		List<Notes> list = notesService.list();
		List<NoteVo> noteVoList = list.stream().map(notes -> {
			String s = JSON.toJSONString(notes);
			NoteVo noteVo = JSON.parseObject(s,NoteVo.class);
			Users byId = usersService.getById(notes.getUserId());
			//查点赞排名(最早点赞在最前面)
			List<String> names = likesService.likedTop5(notes.getId());
			noteVo.setLikedNames(names);
			//查询点赞
			Boolean aBoolean = likesService.LikedByUserId(notes.getId(), uid);
			noteVo.setLikedByUser(aBoolean);
			noteVo.setUsername(byId.getUsername());
			return noteVo;
		}).collect(Collectors.toList());

		return Result.ok(noteVoList);
	}

	@GetMapping("listById")
	public Result listById(@RequestParam Integer uid)
	{
		//select n.*,users.username from notes as n left join users on n.user_id = users.id
		//查询是否点过赞
//		Integer uid = (Integer)httpSession.getAttribute("uid");
		QueryWrapper qw = new QueryWrapper();
		qw.eq("user_id",uid);
		List<Notes> list = notesService.list(qw);
		List<NoteVo> noteVoList = list.stream().map(notes -> {
			String s = JSON.toJSONString(notes);
			NoteVo noteVo = JSON.parseObject(s,NoteVo.class);
			Users byId = usersService.getById(notes.getUserId());
			//查点赞排名(最早点赞在最前面)
			List<String> names = likesService.likedTop5(notes.getId());
			noteVo.setLikedNames(names);
			//查询自己点赞没
//			Boolean aBoolean = likesService.LikedByUserId(notes.getId(), uid);
//			noteVo.setLikedByUser(aBoolean);
			noteVo.setUsername(byId.getUsername());
			return noteVo;
		}).collect(Collectors.toList());

		return Result.ok(noteVoList);
	}
	
	/**
	 * 	如果没有点赞过则点赞，否则反之
	 */
	@Autowired
	StringRedisTemplate stringRedisTemplate;
	
	private static final String NOTE_LIKED_PREFIX = "note:liked:";
	
	@GetMapping("liked")
	public Result liked(HttpSession httpSession,@RequestParam Integer noteId)
	{
		Integer uid = Integer.parseInt( httpSession.getAttribute("uid").toString());
		//查笔记id是否存在
		Notes byId = notesService.getById(noteId);
		if(byId == null)
		{
			return Result.error("笔记不存在");
		}
		
		//查询是否点过赞
		Double score = stringRedisTemplate.opsForZSet().score(NOTE_LIKED_PREFIX + noteId, uid.toString());
		//bu不等于空表示赞过
		if(score != null)
		{
			stringRedisTemplate.opsForZSet().remove(NOTE_LIKED_PREFIX + noteId,uid.toString());
			//减少点赞数
			notesService.update().setSql("like_count = like_count-1").eq("id",noteId).update();
			Map map = new HashMap();
			map.put("likedByUser",false);
			return Result.ok("已取消点赞",map);
		}
		
		long milliseconds = LocalDateTime.now().atZone(ZoneId.systemDefault())
				.toInstant()
				.toEpochMilli();
//		System.out.println("毫秒时间戳: " + milliseconds);
		stringRedisTemplate.opsForZSet().add(NOTE_LIKED_PREFIX+noteId,uid.toString(),milliseconds);
		//增加点赞数
		notesService.update().setSql("like_count = like_count+1").eq("id",noteId).update();
		Map map = new HashMap();
		map.put("likedByUser",true);
		return Result.ok("已点赞",map);
	}
	
	@Autowired
	UserFollowsService userFollowsService;


	
	
	@GetMapping("test")
	public Result test(@RequestParam Integer id)
	{
		likesService.likedTop5(id);
		return Result.ok();
	}


	/**
	 *         {
	 *         id: 1,
	 *         user: {
	 *             name: "张三",
	 *             avatar: "https://randomuser.me/api/portraits/men/1.jpg"
	 *         },
	 *         content: "今天的天气真好，出去走走心情都变好了！",
	 *         images: [
	 *             "https://picsum.photos/id/10/500/500",
	 *             "https://picsum.photos/id/11/500/500",
	 *             "https://picsum.photos/id/12/500/500"
	 *         ],
	 *         time: "10分钟前",
	 *         likes: ["李四", "王五", "赵六"],
	 *         comments: [
	 *             { user: "李四", content: "确实不错！" },
	 *             { user: "王五", content: "下次一起啊" }
	 *         ],
	 *         isLiked: false
	 *     }
	 */
	
	//feed流推模式
	//朋友圈
	@GetMapping("getMoments")
	public Result getMoments()
	{
		Integer uid = (Integer)Current.get("uid");
		
		//首先获取
		Long count = stringRedisTemplate.opsForZSet().zCard(FEED_PREFIX + uid);
		Set<String> range = stringRedisTemplate.opsForZSet().range(FEED_PREFIX + uid, 0, count);
		//添加自己的信息，自己也要能看到
//		range.add(uid.toString());
		
		//获取所有关注的人笔记信息
		List<Notes> notesList = range.size()!= 0?notesService.query().in("id", range.toArray()).list():new ArrayList<>();
		//添加自己的信息，自己也要能看到
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("user_id",uid);
		List list1 = notesService.list(queryWrapper);
		notesList.addAll(list1);

		if(notesList.size() == 0)
		{
			return Result.ok();
		}
		
		List<MomentVo> momentVos = notesList.stream().map(notes -> {
			MomentVo momentVo = new MomentVo();
			//设置作者信息
			Users user = usersService.getById(notes.getUserId());
			momentVo.setId(notes.getId());
			momentVo.setUser(new MomentVo.User(user.getUsername(), user.getAvatar()));
			momentVo.setTitle(notes.getTitle());
			momentVo.setContent(notes.getContent());
			momentVo.setImages(Collections.emptyList());//图片信息
			momentVo.setTime(notes.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			momentVo.setLikes(likesService.likedTop5(notes.getId()));
//			momentVo.setComments(Collections.emptyList());//评论信息
			QueryWrapper qw = new QueryWrapper();
			qw.eq("note_id",notes.getId());
			List<Comments> list = commentsService.list(qw);
			List<MomentVo.Comment> comments = list.stream().map(c -> {

				return new MomentVo.Comment(usersService.getById(c.getUserId()).getUsername(), c.getContent());
			}).toList();
			momentVo.setComments(comments);//评论信息
			
			momentVo.setIsLiked(likesService.LikedByUserId(notes.getId(), uid));
			return momentVo;
		}).toList();
		
		//排序
		momentVos = new ArrayList<MomentVo>(momentVos);//变为可变集合
		momentVos.sort((a,b)->{
//			String dateString = "2023-10-20 14:30:45";

//			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//			LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime aTime = LocalDateTime.parse(a.getTime(), formatter);
			LocalDateTime bTime = LocalDateTime.parse(b.getTime(), formatter);
			Duration duration = Duration.between(aTime, bTime);
			return (int) duration.getSeconds();
			
		});
//		range.stream().map(r->{
//			
//			new MomentVo()	
//		});
		
		return Result.ok(momentVos);
	}

	@Autowired
	CommentsService commentsService;
	
	/**
	 * 评论
	 */
	@GetMapping("sentMessage")
	public Result sentMessage(@RequestParam Integer noteId,@RequestParam String mes)
	{
		Integer uid = (Integer)Current.get("uid");

		Comments comments = new Comments();
		comments.setNoteId(noteId);
		comments.setUserId(uid);
		comments.setContent(mes);
		commentsService.save(comments);
		
		return Result.ok();
	}
	
}
